<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>中山大学刷题平台 - 题解详情</title>
    <!-- 外部CDN资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 代码高亮 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
    <!-- 自定义Tailwind配置 -->
    <link rel="icon" href="{{ url_for('static', filename='favicon.png') }}" type="image/png">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.png') }}" type="image/png">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'sysu-green': '#045525',       // 校色主绿
                        'sysu-lightGreen': '#E6F0EA',  // 浅绿辅助色
                        'sysu-darkGreen': '#03441D',   // 深绿
                        'sysu-gray': '#F7F9FC',        // 浅灰背景色
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .btn-sysu {
                @apply bg-sysu-green text-white px-4 py-2 rounded-lg hover:bg-sysu-darkGreen transition-colors;
            }
            .btn-outline {
                @apply border border-gray-300 bg-white text-gray-700 px-4 py-2 rounded-lg hover:border-sysu-green hover:text-sysu-green transition-colors;
            }
            .card-hover {
                @apply hover:shadow-md transition-shadow duration-300;
            }
            .solution-tag {
                @apply inline-block px-2 py-1 text-xs rounded-full mr-2 mb-2 bg-sysu-lightGreen text-sysu-green;
            }
            .code-block {
                @apply bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto text-sm my-4;
            }
        }
    </style>
</head>
<body class="bg-gray-50 opacity-0 transition-opacity duration-500" id="body">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white border-b border-gray-200 transition-all duration-300 shadow-sm transform translate-y-[-20px] opacity-0" id="header">
        <div class="container mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <!-- 校徽+平台名称 -->
                <div class="flex items-center">
                    <div class="w-10 h-10 bg-sysu-green text-white rounded-lg flex items-center justify-center mr-3">
                        <i class="fa fa-graduation-cap text-xl"></i>
                    </div>
                    <h1 class="text-lg font-bold text-sysu-green">中山大学刷题平台</h1>
                </div>

                <!-- 核心导航（桌面端） -->
                <nav class="hidden md:flex space-x-6">
                    <a href="/" class="text-gray-600 hover:text-sysu-green py-5 transition-colors">首页</a>
                    <a href="/questions" class="text-sysu-green font-medium border-b-2 border-sysu-green py-5">题库</a>
                    <a href="/contests" class="text-gray-600 hover:text-sysu-green py-5 transition-colors">竞赛</a>
                    <a href="/ranking" class="text-gray-600 hover:text-sysu-green py-5 transition-colors">排行榜</a>
                    <a href="/resources" class="text-gray-600 hover:text-sysu-green py-5 transition-colors">学习资源</a>
                </nav>

                <!-- 用户功能区 -->
                <div class="flex items-center space-x-4">
                    <!-- 搜索框 -->
                    <div class="relative hidden sm:block">
                        <input type="text" placeholder="搜索题解"
                               class="pl-8 pr-3 py-2 rounded-lg border border-gray-300 focus:border-sysu-green focus:outline-none text-sm w-40 lg:w-56">
                        <i class="fa fa-search absolute left-3 top-2.5 text-gray-400 text-sm"></i>
                    </div>

                    <!-- 用户区域容器 -->
                    <div class="flex items-center space-x-4" id="user-area-container">
                        <!-- 加载状态 -->
                        <div class="flex items-center" id="loading-indicator">
                            <div class="w-6 h-6 border-2 border-gray-300 border-t-sysu-green rounded-full animate-spin"></div>
                        </div>
                    </div>

                    <!-- 移动端菜单按钮 -->
                    <button class="md:hidden p-2 text-gray-600 hover:text-sysu-green" id="mobile-menu-btn">
                        <i class="fa fa-bars text-lg"></i>
                    </button>
                </div>
            </div>

            <!-- 移动端导航（默认隐藏） -->
            <div class="md:hidden hidden pb-4" id="mobile-menu">
                <div class="flex items-center relative mb-4 mx-2">
                    <input type="text" placeholder="搜索题解"
                           class="w-full pl-8 pr-3 py-2 rounded-lg border border-gray-300 focus:border-sysu-green focus:outline-none text-sm">
                    <i class="fa fa-search absolute left-3 top-2.5 text-gray-400 text-sm"></i>
                </div>
                <nav class="flex flex-col space-y-2 mx-2">
                    <a href="/" class="text-gray-600 px-2 py-2 hover:bg-sysu-lightGreen rounded">首页</a>
                    <a href="/questions" class="text-sysu-green px-2 py-2 bg-sysu-lightGreen rounded font-medium">题库</a>
                    <a href="/contests" class="text-gray-600 px-2 py-2 hover:bg-sysu-lightGreen rounded">竞赛</a>
                    <a href="/ranking" class="text-gray-600 px-2 py-2 hover:bg-sysu-lightGreen rounded">排行榜</a>
                    <a href="/resources" class="text-gray-600 px-2 py-2 hover:bg-sysu-lightGreen rounded">学习资源</a>
                </nav>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-6">
        <!-- 题解标题区域 -->
        <div class="mb-8 opacity-0 transform translate-y-[20px]" id="solution-header">
            <div class="flex items-center text-sm text-gray-500 mb-3">
                <a href="/questions" class="hover:text-sysu-green transition-colors">题库</a>
                <i class="fa fa-angle-right mx-2 text-gray-400 text-xs"></i>
                <a href="/questions/{{ id }}" class="hover:text-sysu-green transition-colors">题目 #{{ id }}</a>
                <i class="fa fa-angle-right mx-2 text-gray-400 text-xs"></i>
                <span>题解</span>
            </div>

            <h1 class="text-2xl md:text-3xl font-bold text-gray-800 mb-4">题目 #{{ id }} 题解：两数之和最优解法</h1>

            <div class="flex flex-wrap items-center gap-4 mb-6">
                <div class="flex items-center">
                    <img src="https://picsum.photos/id/1005/40/40" alt="作者头像" class="w-10 h-10 rounded-full mr-3">
                    <div>
                        <p class="font-medium">张同学</p>
                        <p class="text-xs text-gray-500">发布于 2023-05-15</p>
                    </div>
                </div>

                <div class="flex items-center text-gray-500 space-x-6">
                    <div class="flex items-center">
                        <i class="fa fa-eye mr-1"></i>
                        <span class="text-sm">1,243</span>
                    </div>
                    <div class="flex items-center">
                        <i class="fa fa-thumbs-up mr-1"></i>
                        <span class="text-sm">87</span>
                    </div>
                    <div class="flex items-center">
                        <i class="fa fa-comment mr-1"></i>
                        <span class="text-sm">23</span>
                    </div>
                </div>
            </div>

            <div class="flex flex-wrap gap-2 mb-6">
                <span class="solution-tag">哈希表</span>
                <span class="solution-tag">O(n)时间复杂度</span>
                <span class="solution-tag">简单</span>
            </div>
        </div>

        <!-- 题解内容区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- 主要内容 -->
            <div class="lg:col-span-2 bg-white rounded-xl shadow-sm p-6 md:p-8">
                <div class="prose max-w-none">
                    <h2>解题思路</h2>
                    <p>本题要求找出数组中和为目标值的两个整数，并返回它们的索引。常规解法使用双重循环暴力破解，时间复杂度为 O(n²)，效率较低。</p>

                    <p>优化方案采用哈希表（JavaScript 中的 Map 对象）存储已经遍历过的元素及其索引，每次遍历到新元素时，计算目标值与当前元素的差值，检查该差值是否已存在于哈希表中：</p>

                    <ul>
                        <li>如果存在，则直接返回当前索引与哈希表中存储的索引</li>
                        <li>如果不存在，则将当前元素及其索引存入哈希表</li>
                    </ul>

                    <p>这种方法只需遍历一次数组，时间复杂度为 O(n)，空间复杂度为 O(n)，是本题的最优解法。</p>

                    <h2>代码实现</h2>
                    <pre><code class="language-javascript">/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    // 创建哈希表存储已遍历的元素
    const map = new Map();

    // 遍历数组
    for (let i = 0; i < nums.length; i++) {
        // 计算需要寻找的目标值
        const complement = target - nums[i];

        // 检查哈希表中是否存在该目标值
        if (map.has(complement)) {
            // 存在则返回结果
            return [map.get(complement), i];
        }

        // 不存在则将当前元素加入哈希表
        map.set(nums[i], i);
    }

    // 题目保证有解，此处无需处理无结果情况
    return [];
};</code></pre>

                    <h2>复杂度分析</h2>
                    <ul>
                        <li><strong>时间复杂度</strong>：O(n)，其中 n 是数组的长度。我们只需要遍历一次数组。</li>
                        <li><strong>空间复杂度</strong>：O(n)，主要为哈希表的开销，最坏情况下需要存储所有元素。</li>
                    </ul>

                    <h2>扩展思考</h2>
                    <p>如果数组中存在多个解，该算法只会返回第一个找到的解。如果需要返回所有可能的解，需要稍作修改：</p>
                    <ol>
                        <li>使用数组存储所有符合条件的索引对</li>
                        <li>遍历完成后返回该数组</li>
                    </ol>
                </div>

                <!-- 点赞和收藏按钮 -->
                <div class="flex justify-between items-center mt-10 pt-6 border-t border-gray-100">
                    <button class="btn-outline flex items-center">
                        <i class="fa fa-thumbs-up mr-2"></i> 点赞 (87)
                    </button>
                    <button class="btn-outline flex items-center">
                        <i class="fa fa-bookmark-o mr-2"></i> 收藏
                    </button>
                    <button class="btn-outline flex items-center">
                        <i class="fa fa-share-alt mr-2"></i> 分享
                    </button>
                </div>

                <!-- 评论区 -->
                <div class="mt-10">
                    <h3 class="text-xl font-bold mb-6">评论 (23)</h3>

                    <!-- 评论输入框 -->
                    <div class="mb-8">
                        <textarea placeholder="分享你的解题思路..." class="w-full p-4 border border-gray-300 rounded-lg focus:border-sysu-green focus:outline-none resize-none h-24"></textarea>
                        <div class="flex justify-end mt-3">
                            <button class="btn-sysu">发布评论</button>
                        </div>
                    </div>

                    <!-- 评论列表 -->
                    <div class="space-y-6">
                        <!-- 评论项1 -->
                        <div class="flex gap-4">
                            <img src="https://picsum.photos/id/1012/40/40" alt="评论者头像" class="w-10 h-10 rounded-full">
                            <div class="flex-1">
                                <div class="bg-gray-50 p-4 rounded-lg">
                                    <div class="flex justify-between items-start mb-2">
                                        <h4 class="font-medium">李同学</h4>
                                        <span class="text-xs text-gray-500">3天前</span>
                                    </div>
                                    <p class="text-gray-700 text-sm">这个解法很清晰，我之前一直用双重循环，学到了！</p>
                                </div>
                                <div class="flex items-center mt-2 text-sm text-gray-500">
                                    <button class="flex items-center hover:text-sysu-green transition-colors">
                                        <i class="fa fa-thumbs-up mr-1"></i> 12
                                    </button>
                                    <span class="mx-3">|</span>
                                    <button class="hover:text-sysu-green transition-colors">回复</button>
                                </div>
                            </div>
                        </div>

                        <!-- 评论项2 -->
                        <div class="flex gap-4">
                            <img src="https://picsum.photos/id/1025/40/40" alt="评论者头像" class="w-10 h-10 rounded-full">
                            <div class="flex-1">
                                <div class="bg-gray-50 p-4 rounded-lg">
                                    <div class="flex justify-between items-start mb-2">
                                        <h4 class="font-medium">王同学</h4>
                                        <span class="text-xs text-gray-500">1周前</span>
                                    </div>
                                    <p class="text-gray-700 text-sm">请问如果数组中有重复元素会有问题吗？比如 [3,3] 目标值 6 的情况。</p>
                                </div>
                                <div class="flex items-center mt-2 text-sm text-gray-500">
                                    <button class="flex items-center hover:text-sysu-green transition-colors">
                                        <i class="fa fa-thumbs-up mr-1"></i> 5
                                    </button>
                                    <span class="mx-3">|</span>
                                    <button class="hover:text-sysu-green transition-colors">回复</button>

                                    <!-- 嵌套回复 -->
                                    <div class="mt-4 ml-6 flex gap-3">
                                        <img src="https://picsum.photos/id/1005/30/30" alt="回复者头像" class="w-8 h-8 rounded-full">
                                        <div class="flex-1">
                                            <div class="bg-gray-50 p-3 rounded-lg">
                                                <div class="flex justify-between items-start mb-1">
                                                    <h5 class="font-medium text-sm">张同学 <span class="text-xs text-gray-500">（作者）</span></h5>
                                                    <span class="text-xs text-gray-500">6天前</span>
                                                </div>
                                                <p class="text-gray-700 text-sm">不会有问题，因为我们是先检查再存入哈希表，所以会返回正确的索引 [0,1]。</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 加载更多评论 -->
                    <div class="text-center mt-8">
                        <button class="btn-outline">查看更多评论</button>
                    </div>
                </div>
            </div>

            <!-- 侧边栏 -->
            <div class="space-y-6">
                <!-- 题目信息卡片 -->
                <div class="bg-white rounded-xl shadow-sm p-6 card-hover">
                    <h3 class="font-bold text-lg mb-4">相关题目</h3>
                    <div class="border-b border-gray-100 pb-4 mb-4">
                        <h4 class="font-medium mb-2">两数之和</h4>
                        <p class="text-sm text-gray-500 mb-3">给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出 和为目标值 target 的那 两个 整数，并返回它们的数组下标。</p>
                        <div class="flex justify-between items-center">
                            <span class="inline-block px-2 py-1 text-xs rounded-full bg-green-100 text-green-800">简单</span>
                            <a href="/questions/{{ id }}" class="text-sysu-green hover:underline text-sm">查看题目</a>
                        </div>
                    </div>

                    <h4 class="font-medium mb-3">相似题目</h4>
                    <ul class="space-y-3">
                        <li class="flex justify-between items-center">
                            <a href="/questions/15" class="text-gray-700 hover:text-sysu-green text-sm">三数之和</a>
                            <span class="text-xs text-gray-500">中等</span>
                        </li>
                        <li class="flex justify-between items-center">
                            <a href="/questions/18" class="text-gray-700 hover:text-sysu-green text-sm">四数之和</a>
                            <span class="text-xs text-gray-500">中等</span>
                        </li>
                        <li class="flex justify-between items-center">
                            <a href="/questions/454" class="text-gray-700 hover:text-sysu-green text-sm">四数相加 II</a>
                            <span class="text-xs text-gray-500">中等</span>
                        </li>
                    </ul>
                </div>

                <!-- 推荐题解 -->
                <div class="bg-white rounded-xl shadow-sm p-6 card-hover">
                    <h3 class="font-bold text-lg mb-4">更多题解</h3>
                    <ul class="space-y-4">
                        <li>
                            <a href="/solutions/{{ id }}?version=2" class="text-gray-700 hover:text-sysu-green">
                                <h4 class="font-medium text-sm mb-1">两数之和的多种解法对比</h4>
                                <p class="text-xs text-gray-500">包含暴力法、哈希表法、双指针法的详细对比</p>
                            </a>
                        </li>
                        <li>
                            <a href="/solutions/{{ id }}?version=3" class="text-gray-700 hover:text-sysu-green">
                                <h4 class="font-medium text-sm mb-1">C++实现：两数之和最优解</h4>
                                <p class="text-xs text-gray-500">使用C++ STL中的unordered_map实现</p>
                            </a>
                        </li>
                        <li>
                            <a href="/solutions/{{ id }}?version=4" class="text-gray-700 hover:text-sysu-green">
                                <h4 class="font-medium text-sm mb-1">Python一行代码解决两数之和</h4>
                                <p class="text-xs text-gray-500">利用列表推导式和enumerate函数</p>
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </main>

    <script>
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化代码高亮
            hljs.highlightAll();

            // 检查登录状态
            checkLoginStatus();

            // 初始化动画效果
            initAnimations();

            // 移动端菜单切换
            const mobileMenuBtn = document.getElementById('mobile-menu-btn');
            const mobileMenu = document.getElementById('mobile-menu');

            if (mobileMenuBtn && mobileMenu) {
                mobileMenuBtn.addEventListener('click', function() {
                    mobileMenu.classList.toggle('hidden');
                });
            }
        });

        // 检查登录状态
        async function checkLoginStatus() {
            const container = document.getElementById('user-area-container');
            const loadingIndicator = document.getElementById('loading-indicator');

            if (!container) return;

            try {
                const token = localStorage.getItem('token');
                const response = await fetch('/api/check_login', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    }
                });

                if (!response.ok) {
                    throw new Error('验证请求失败');
                }

                const data = await response.json();

                if (data.is_logged_in) {
                    renderLoggedInView(container, data || {});
                } else {
                    renderLoggedOutView(container);
                }
            } catch (error) {
                console.error('登录状态验证出错:', error);
                renderLoggedOutView(container);
            } finally {
                if (loadingIndicator) {
                    loadingIndicator.remove();
                }
            }
        }

        // 渲染已登录视图
        function renderLoggedInView(container, userData) {
            container.innerHTML = `
                <div class="relative" id="userDropdown">
                    <button class="flex items-center space-x-2 focus:outline-none cursor-pointer" id="dropdownTrigger">
                        <img src="${'http://localhost:5000/api/v1/avatar/' + userData.user_id || 'https://picsum.photos/id/1005/40/40'}"
                             alt="${userData.username || '用户头像'}"
                             class="w-8 h-8 rounded-full border-2 border-transparent hover:border-sysu-green transition-colors">
                        <i class="fa fa-angle-down text-gray-500 hidden sm:block transition-transform duration-300" id="dropdownIcon"></i>
                    </button>
                    <div class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-2 hidden z-50" id="dropdownMenu">
                        <a href="/profile/${ userData.user_id }" class="block px-4 py-2 text-gray-700 hover:bg-sysu-lightGreen hover:text-sysu-green transition-colors">个人中心</a>
                        <a href="/my_progress/${ userData.user_id }" class="block px-4 py-2 text-gray-700 hover:bg-sysu-lightGreen hover:text-sysu-green transition-colors">学习进度</a>
                        <a class="block px-4 py-2 text-gray-700 hover:bg-sysu-lightGreen hover:text-sysu-green transition-colors" onclick="logout()">退出登录</a>
                    </div>
                </div>
            `;

            // 绑定下拉菜单事件
            bindDropdownEvents();
        }

        // 渲染未登录视图
        function renderLoggedOutView(container) {
            container.innerHTML = `
                <div class="flex items-center space-x-3">
                    <a href="/login" class="text-gray-600 hover:text-sysu-green transition-colors px-3 py-2 rounded-md text-sm font-medium">
                        登录
                    </a>
                    <a href="/register" class="bg-sysu-green text-white px-3 py-2 rounded-md text-sm font-medium hover:bg-sysu-darkGreen transition-colors">
                        注册
                    </a>
                </div>
            `;
        }

        // 绑定下拉菜单事件
        function bindDropdownEvents() {
            const trigger = document.getElementById('dropdownTrigger');
            const menu = document.getElementById('dropdownMenu');
            const icon = document.getElementById('dropdownIcon');

            if (trigger && menu && icon) {
                trigger.addEventListener('click', function() {
                    menu.classList.toggle('hidden');
                    icon.classList.toggle('rotate-180');
                });

                // 点击外部关闭下拉菜单
                document.addEventListener('click', function(event) {
                    if (!trigger.contains(event.target) && !menu.contains(event.target)) {
                        menu.classList.add('hidden');
                        icon.classList.remove('rotate-180');
                    }
                });
            }
        }

        // 退出登录
        function logout() {
            try {
                const token = localStorage.getItem('token');
                fetch('/api/v1/logout', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    }
                }).then(() => {
                    localStorage.removeItem('token');
                    window.location.href = '/';
                });
            } catch (error) {
                console.error('退出登录出错:', error);
            }
        }

        // 初始化动画效果
        function initAnimations() {
            // 页面整体淡入
            setTimeout(() => {
                document.getElementById('body').classList.add('opacity-100');
            }, 100);

            // 导航栏滑入
            setTimeout(() => {
                const header = document.getElementById('header');
                if (header) {
                    header.classList.remove('translate-y-[-20px]', 'opacity-0');
                }
            }, 200);

            // 标题区域淡入
            setTimeout(() => {
                const header = document.getElementById('solution-header');
                if (header) {
                    header.classList.remove('opacity-0', 'translate-y-[20px]');
                    header.style.transition = 'opacity 0.5s ease-out, transform 0.5s ease-out';
                }
            }, 300);
        }
    </script>
</body>
</html>